import './add.less';
import Panel from "./../../elements/Panel";
import Header from "./../../components/Header";
import Modal from "./../../components/Modal/";
import {connect} from "react-redux";
import CONFIG from "./../../libs/config";
import {Lang, Fetch} from "./../../libs/";
import {URL, md5Url} from "./../../libs/Url";
import Label from "./../../components/FormLabel";
import FormGroup from "./../../components/FormGroup";
import FormItem from "./../../components/FormItem";
import Lesson from "./../../components/form/lesson";
import FormItemType from "./../../components/FormItemType";
import InputGroup from "./../../components/InputGroup";
import Selected from "./../../components/SelectItem";
import {Warn} from "./../../components/alert/";
import BreadcrumbNavigation from "./../../components/BreadcrumbNavigation";
import SingleSelectClass from "./../../components/form/single_select_class";
import {fetch, fetchUser} from "../../actions";
import {SUBJECT, PAGE_SUBJECT} from "./../../actions/subject";


const AddTeachSchedule = React.createClass({
    getInitialState(){
        const self = this;
        let form = [
            {
                label: '科目',
                value: '',
                type: FormItemType.TEXT_SHOW,
            },
            {
                label: '教师',
                value: '',
                type: FormItemType.TEXT_SHOW,
            },
            {
                name: 'classid',
                label: '推送班级',
                value: '',
                required: true,
                tips: '',
                type: FormItemType.MODAL_CHECK_BOX,
            },
            {
                name: 'title',
                label: '标题',
                placeholder: '',
                required: true,
                value: '',
                tips: '',
                type: FormItemType.INPUT,
            },
            {
                name: 'summary',
                label: '学情分析',
                required: false,
                value: '',
                placeholder: '',
                tips: '',
            },
            {
                name: 'summary',
                label: '教学目标',
                required: false,
                value: '',
                placeholder: '',
                tips: '',
            },
            {
                name: 'summary',
                label: '重点难点',
                required: false,
                value: '',
                placeholder: '',
                tips: '',
            },
            {
                name: 'summary',
                label: '备注',
                value: '',
                placeholder: '',
                tips: '',
            },
        ];
        form.map((item, index)=> {
            if (FormItemType.TEXT_SHOW != item.type)
                item.onchange = (index, content) => {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                };
            return item;
        });
        return {
            open: false,
            selected: '',
            pageState: false,
            form: form,
            tmpForm: [],//表单缓存变量
            tmp: {
                push_class: ''
            },
            tips: {}
        }
    },
    setchange(index, content){
        const self = this;
        self.setState({
            form: [
                ...self.state.form.slice(0, index),
                Object.assign({}, self.state.form[index], {
                    value: content,
                    tips: content.length ? '' : Lang.NEWS_CREATE.tip,
                }),
                ...self.state.form.slice(index + 1),
            ]
        })
    },
    componentDidMount() {
        const {dispatch} = this.props;
        dispatch(fetchUser(SUBJECT.NEWS_CATEGORY));
        dispatch(fetch({url: URL.CATEGORY_FIND}))
    },

    cloneArray(arr){
        var self = this;
        return arr.map(item=> {
            return self.deepClone(item);
        });
    },
    deepClone(obj) {
        var self = this;
        var o = obj instanceof Array ? [] : {};
        for (var k in obj)
            o[k] = typeof obj[k] === Object ? self.deepClone(obj[k]) : obj[k];
        return o;
    },
    onsubmit(){
        const self = this;
        if (self.state.pageState) {
            self.setState({
                tmpForm: [],
                form: self.cloneArray(self.state.tmpForm),
                pageState: false
            })
        } else {
            const tmp = self.cloneArray(self.state.form);
            self.setState({
                tmpForm: tmp,
                form: self.state.form.map(item=> {
                    item.type = FormItemType.TEXT_SHOW;
                    return item;
                }),
                pageState: true
            });
        }
        return;
        const {dispatch} = this.props;
        var form = {};
        self.state.form.forEach((item, index)=> {
            if (item.required && item.value.length == 0) {
                self.setState({
                    form: [
                        ...self.state.form.slice(0, index),
                        Object.assign({}, self.state.form[index], {
                            tips: Lang.NEWS_CREATE.tip,
                        }),
                        ...self.state.form.slice(index + 1),
                    ]
                })
            } else {
                form[item.name] = item.value
            }
        });
        if (Object.keys(form).length == self.state.form.length) {
            form.classid = form.classid.slice(1);
            form.url = URL.NEWS_ADD;
            Fetch(URL.NEWS_ADD, {body: form})
                .then(data=> {
                    console.log(data);
                    alert('创建成功!')
                })
                .catch(e=> {
                    alert('创建失败');
                    console.log(e)
                })
        }
    },
    render(){

        const self = this;
        const {user, dispatch}  = this.props;
        const form = this.props[PAGE_SUBJECT.NEWS_ADD].form;
        const data_category = self.props[md5Url.CATEGORY_FIND] || {};
        (!data_category.list && (data_category.list = []));

        return (
            <div>
                <BreadcrumbNavigation navs={[
                    {url: CONFIG.MENUS.HOME, label: Lang.menus.HOME},
                    {url: CONFIG.MENUS.TEACH_SCHEDULE, label: Lang.menus.TEACH_SCHEDULE},
                    {label: Lang.menus.TEACH_SCHEDULE_ADD},
                ]}>
                </BreadcrumbNavigation>
                <Panel>
                    <Header>{Lang.menus.TEACH_SCHEDULE_ADD}</Header>
                    <Warn>
                        <strong>说明：</strong>1、添加本学期的教学计划总纲； 2.保存成功后，可进行课时安排的添加；
                    </Warn>
                    <h5 className="add-h5">教学计划总纲</h5>
                    <div className="form-horizontal">
                        {
                            self.state.form.map((item, index)=> {
                                if (index == 0) {
                                    item.value = user.name;
                                } else if (index == 1) {
                                    item.value = user.teacher ? user.teacher.subject.name : '';
                                }
                                if (item.type == FormItemType.MODAL_CHECK_BOX) {
                                    return <FormItem {...item} key={index}>
                                        <div className="homeword">
                                            {
                                                user.class.map((item_, idex)=> {
                                                    item_.checked = self.state.form[index].value.indexOf(item_.class ? item_.class.id : item_.id) > -1;
                                                    return <Selected onremove={()=> {
                                                        return item.onchange(index, '');
                                                    }} key={idex} {...item_} />
                                                })
                                            }
                                            <button className="btn btn-default btn-sm " onClick={()=> {
                                                this.setState({open: true})
                                            }} type="button"><i className="fa fa-hand-o-up"></i> 推送班级
                                            </button>
                                        </div>
                                        <Modal open={self.state.open}>
                                            <Modal.Header onclose={()=> {
                                                self.setState({
                                                    open: false,
                                                    selected: '',
                                                    tmp: Object.assign({}, self.state.tmp, {push_class: ''})
                                                })
                                            }}>{Lang.NEWS_CREATE.choose}</Modal.Header>
                                            <Modal.Body>
                                                <SingleSelectClass class={user.class}
                                                                   onchange={(data)=> {
                                                                       console.log(data);
                                                                       self.setState({
                                                                           tmp: Object.assign({}, self.state.tmp, {push_class: data})
                                                                       });
                                                                   }}
                                                />
                                            </Modal.Body>
                                            <Modal.Footer
                                                onclose={()=> {
                                                    self.setState({
                                                        open: false, selected: '',
                                                        tmp: Object.assign({}, self.state.tmp, {push_class: ''})
                                                    });
                                                }}
                                                onconfirm={()=> {
                                                    item.onchange(index, _.union(self.state.form[index].value.split(','),
                                                            self.state.selected.split(',')).join(',') + ',');
                                                    self.setState({
                                                        open: false, selected: '',
                                                        form: [
                                                            ...self.state.form.slice(0, 2),
                                                            Object.assign({}, self.state.form[2], {value: self.state.tmp.push_class}),
                                                            ...self.state.form.slice(3)],
                                                        tmp: Object.assign({}, self.state.tmp, {push_class: ''})
                                                    });
                                                }}
                                            />
                                        </Modal>
                                    </FormItem>
                                } else if (item.type == FormItemType.SELECT) {
                                    return <FormItem {...item} key={index}>
                                        <select className="form-control" onChange={(e)=> {
                                            item.onchange(index, e.target.value)
                                        }}>
                                            {
                                                data_category.list.map(function (item_, index) {
                                                    return <option value={item_.id} key={index}>{item_.name}</option>
                                                })
                                            }
                                        </select>
                                    </FormItem>
                                } else {
                                    return <FormItem index={index} {...item} key={index}></FormItem>
                                }
                            })
                        }
                        <FormGroup>
                            <Label></Label>
                            <InputGroup>
                                <button onClick={self.onsubmit}
                                        className={"btn btn-success " + (self.state.pageState ? 'btn-primary' : '')}
                                        type="submit">
                                    {self.state.pageState ? '编辑' : Lang.NEWS_CREATE.save}
                                    {this.props[PAGE_SUBJECT.NEWS_ADD].isFetching ? '...' : ''}
                                </button>
                            </InputGroup>
                        </FormGroup>
                    </div>
                    {
                        self.state.pageState ? <div>
                            <h5 className="add-h5">课时安排</h5>
                            <div className="lessonPlan">
                                <div className="panel-body">
                                    <table className="table table-striped general-table">
                                        <thead>
                                        <tr>
                                            <th style={{width: '50px'}}>NO.</th>
                                            <th>课时计划名称</th>
                                            <th>推送时间</th>
                                            <th style={{width: '80px'}}>操作</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <tr>
                                            <td className="hidden-phone">1</td>
                                            <td><a href="#" target="_blank">(一)、时、分、秒……（6课时）</a></td>
                                            <td> 2016-12-06</td>
                                            <td>
                                                <a href="#" className="btn btn-default btn-xs">
                                                    <i className="fa fa-pencil"></i>
                                                </a>
                                                <button data-toggle="modal" href="#myModal"
                                                        className="btn btn-default btn-xs">
                                                    <i className="fa fa-times"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td className="hidden-phone">2</td>
                                            <td>
                                                <a href="#" target="_blank">(一)、时、分、秒……（6课时）</a>
                                                <a href="新闻详情.html" target="_blank"></a>
                                                <i className="fa fa-paperclip"></i>
                                            </td>
                                            <td>2016-12-08、2016-12-09</td>
                                            <td>
                                                <a href="#" className="btn btn-default btn-xs">
                                                    <i className="fa fa-pencil"></i>
                                                </a>
                                                <button data-toggle="modal" href="#myModal"
                                                        className="btn btn-default btn-xs"
                                                        type="button" data-target=".bs-example-modal-sm">
                                                    <i className="fa fa-times"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td className="hidden-phone">3</td>
                                            <td>
                                                <a href="#" target="_blank">(一)、时、分、秒……（6课时）</a>
                                                <a href="新闻详情.html" target="_blank"></a>
                                                <i className="fa fa-paperclip"></i>
                                            </td>
                                            <td>未设置</td>
                                            <td>
                                                <a href="#" className="btn btn-default btn-xs">
                                                    <i className="fa fa-pencil"></i>
                                                </a>
                                                <button data-toggle="modal" href="#myModal"
                                                        className="btn btn-default btn-xs"
                                                        type="button" data-target=".bs-example-modal-sm">
                                                    <i className="fa fa-times"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td className="hidden-phone">4</td>
                                            <td><a href="#" target="_blank">(一)、时、分、秒……（6课时）</a><a href="新闻详情.html"
                                                                                                   target="_blank"></a>
                                            </td>
                                            <td> 2016-12-06</td>
                                            <td><a href="#" className="btn btn-default btn-xs"><i
                                                className="fa fa-pencil"></i></a>
                                                <button data-toggle="modal" href="#myModal"
                                                        className="btn btn-default btn-xs"
                                                        type="button" data-target=".bs-example-modal-sm"><i
                                                    className="fa fa-times"></i></button>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td className="hidden-phone">5</td>
                                            <td><a href="#" target="_blank">(一)、时、分、秒……（6课时）</a>
                                                <a href="新闻详情.html" target="_blank"></a>
                                            </td>
                                            <td> 2016-12-06</td>
                                            <td>
                                                <a href="#" className="btn btn-default btn-xs">
                                                    <i className="fa fa-pencil"></i>
                                                </a>
                                                <button data-toggle="modal" href="#myModal"
                                                        className="btn btn-default btn-xs"
                                                        type="button" data-target=".bs-example-modal-sm"><i
                                                    className="fa fa-times"></i></button>
                                            </td>
                                        </tr>
                                        </tbody>
                                    </table>
                                    <Modal open={self.state.open}>
                                        <Modal.Header onclose={()=> {
                                            self.setState({open: false, selected: ''})
                                        }
                                        }>{Lang.NEWS_CREATE.choose}</Modal.Header>
                                        <Modal.Body >
                                            <Lesson></Lesson>
                                        </Modal.Body>
                                        <Modal.Footer
                                            onclose={()=> {
                                                self.setState({open: false, selected: ''})
                                            }}
                                            onconfirm={()=> {
                                                self.setState({open: false, selected: ''})
                                            }}
                                        />
                                    </Modal>
                                    <div className="row table-list-head">
                                        <div className="col-md-6">
                                            <a onClick={()=> {
                                                self.setState({open: true, selected: ''})
                                            }} href="javascript:void(0);" className="btn btn-primary btn-sm">
                                                <i className="fa fa-plus"> 新建课时计划</i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div> : ''
                    }

                </Panel>
            </div>
        )
    }
});
function select(state) {
    return {
        user: state.user_login.user,
        [md5Url.CATEGORY_FIND]: state.fetchBySubject[md5Url.CATEGORY_FIND],
        [md5Url.NEWS_ADD]: state.fetchBySubject[md5Url.NEWS_ADD],
        [PAGE_SUBJECT.NEWS_ADD]: state.pageBySubject[PAGE_SUBJECT.NEWS_ADD]
    }
}
export default connect(select)(AddTeachSchedule)